package sessionBeans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.Cliente;
import entities.FacturaVenta;
import exceptions.EntityAlreadyExistException;

/**
 * Session Bean implementation class AdministradorVentasBean
 */
@Stateless
public class AdministradorVentasBean implements AdministradorVentas {

	@PersistenceContext(unitName="CRM")
    private EntityManager em;
	
	public AdministradorVentasBean() {
        // TODO Auto-generated constructor stub
    }
    
	@SuppressWarnings("unchecked")
	@Override
	public FacturaVenta buscarFactura(int nroComanda) {
		Query q = em.createQuery("from FacturaVenta a where a.nroComanda = :comanda");
		q.setParameter("comanda", nroComanda);
		FacturaVenta factura = null;
		List<FacturaVenta> facturas = (ArrayList<FacturaVenta>) q.getResultList();
		if(!facturas.isEmpty()){
			factura = facturas.get(0);
		}
		return factura;
	}

	@Override
	public boolean grabarFactura(FacturaVenta factura)
			throws EntityAlreadyExistException {
		FacturaVenta factu = this.buscarFactura(factura.getNroComanda());
		if(factu!=null){
			throw new EntityAlreadyExistException("FacturaVenta" + factura.getNroComanda());
		}
		try{
			this.em.persist(factura);
			return true;
		} catch (Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FacturaVenta> getAllFacturaVentas() {
		Query q = em.createQuery("from FacturaVenta");
		List<FacturaVenta> facturas = (ArrayList<FacturaVenta>) q.getResultList();
		return facturas;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FacturaVenta> getFacturasDeCliente(Cliente cli) {
		Query q = em.createQuery("from FacturaVenta a where a.cliente = :cli");
		q.setParameter("cli", cli);
		List<FacturaVenta> facturas = (ArrayList<FacturaVenta>) q.getResultList();
		return facturas;
	}
}
